package com.weishu.system.controller;

import com.weishu.system.config.ContractListenter;
import com.weishu.system.domain.PayMentPlan;
import com.weishu.system.domain.TSfContract;
import com.weishu.system.mapper.TSfContractMapper;
import com.weishu.system.service.ITSfContractService;
import com.weishu.system.service.ITSfTerminationService;


import com.weishu.common.core.domain.R;
import com.weishu.common.core.utils.poi.ExcelUtil;
import com.weishu.common.core.web.controller.BaseController;
import com.weishu.common.core.web.domain.AjaxResult;
import com.weishu.common.core.web.page.TableDataInfo;
import com.weishu.common.log.annotation.Log;
import com.weishu.common.log.enums.BusinessType;
import com.weishu.common.security.annotation.PreAuthorize;
//import com.weishu.system.api.RemoteFileService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2021-06-18
 */
@RestController
@RequestMapping("/contract")
public class TSfContractController extends BaseController
{

    @Autowired
    private ITSfTerminationService terminationService;

    @Autowired
    private ITSfContractService tSfContractService;

//    @Resource
//    private RemoteFileService fileService;



    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize(hasPermi = "core:contract:list")
    @GetMapping("/list")
    public TableDataInfo list(TSfContract tSfContract)

    {

        startPage();
        List<TSfContract> list = tSfContractService.selectTSfContractList(tSfContract);
        System.err.println("dsdasdsa");
        list.forEach(r->{
            System.err.println(r+"sdasdsadsad");
        });
        return getDataTable(list);
    }


    @PreAuthorize(hasPermi = "core:contract:querylist")
    @GetMapping("/querylist")
    public TableDataInfo querylist(TSfContract tSfContract)
    {
        startPage();
        List<TSfContract> list = tSfContractService.querylist(tSfContract);
        return getDataTable(list);
    }

    @PreAuthorize(hasPermi = "core:contract:ownerlist")
    @GetMapping("/ownerlist")
    public TableDataInfo ownerlist(TSfContract tSfContract)
    {
        startPage();
        List<TSfContract> list = tSfContractService.selectTSOwnerList(tSfContract);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize(hasPermi = "core:contract:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TSfContract tSfContract) throws IOException
    {
        List<TSfContract> list = tSfContractService.selectTSfContractList(tSfContract);
        ExcelUtil<TSfContract> util = new ExcelUtil<TSfContract>(TSfContract.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize(hasPermi = "core:contract:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tSfContractService.selectTSfContractById(id));
    }

   /* @PreAuthorize(hasAnyPermi = "houseClosing:contract:upload")
    @PostMapping("upload")
    public Object upload(MultipartFile file){
        return  fileService.upload(file).getData().getUrl();
    }*/



    @PreAuthorize(hasPermi = "core:contract:query")
//    @Log(title = "添加收房合同", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody TSfContract tSfContract) throws ParseException {


        //获取时间差的月份
        List<String> list =new ArrayList();

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();

        Date leaseStartTime = tSfContract.getLeaseStartTime();
        String strDate = sdf.format(leaseStartTime);

        Date startTime = sdf.parse(strDate);

        Date leaseEndTime = tSfContract.getLeaseEndTime();
        String endDate = sdf.format(leaseEndTime);
        Date endTime= sdf.parse(endDate);
        Date start=new Date(startTime.getTime());
        Date end= new Date(endTime.getTime());


        calendar1.setTime(start);
        calendar2.setTime(end);

        int year=  calendar2.get(Calendar.YEAR)-calendar1.get(Calendar.YEAR);
        int month= calendar2.get(Calendar.MONTH)+year*12-calendar1.get(Calendar.MONTH);
        int u=0;
        for(int i=0;i<=month;i++){
            calendar1.setTime(startTime);
            calendar1.add(Calendar.MONTH,i);
            if(i==u){
                u= (int) (i+tSfContract.getPaymentType());
                list.add(sdf.format(calendar1.getTime()));
            }
            if(i==month){
                list.add(sdf.format(calendar1.getTime()));
            }
        }
        List<PayMentPlan> CwList=new ArrayList<>();
        //押金
        PayMentPlan PayMentPlan2=new PayMentPlan();
        PayMentPlan2.setPaymentAmount(tSfContract.getDepositMoney());
        PayMentPlan2.setSkStatus(1);
            PayMentPlan2.setPayNumber(1);
            CwList.add(PayMentPlan2);
            for(int i=0;i<list.size()-1;i++){

            PayMentPlan cwPaymentPlanDto=new PayMentPlan();
            cwPaymentPlanDto.setPaymentDaysBegin(list.get(i));
            cwPaymentPlanDto.setPayableDate(list.get(i));
            cwPaymentPlanDto.setPayNumber(i+1);
            tSfContract.getMonthRent().multiply(BigDecimal.valueOf(tSfContract.getPaymentType()));
            //支付金额
            cwPaymentPlanDto.setPaymentAmount( tSfContract.getMonthRent().multiply(BigDecimal.valueOf(tSfContract.getPaymentType())));

            cwPaymentPlanDto.setPaymentDaysEnd(list.get(i+1));


            CwList.add(cwPaymentPlanDto);
            System.out.println(cwPaymentPlanDto);

        }
        PayMentPlan cwPaymentPlanDto = CwList.get(1);
        PayMentPlan cwPaymentPlanDto2 = CwList.get(0);
        cwPaymentPlanDto2.setPaymentDaysBegin(cwPaymentPlanDto.getPaymentDaysBegin());
        cwPaymentPlanDto2.setPaymentDaysEnd(cwPaymentPlanDto.getPaymentDaysEnd());
        cwPaymentPlanDto2.setPayableDate(cwPaymentPlanDto.getPayableDate());


        return R.ok(CwList);


    }
    //生成合同
    @PostMapping("scht")
    @ResponseBody
    public AjaxResult scht(@RequestBody TSfContract tSfContract) throws IOException, TemplateException {
        System.out.println(tSfContract+"1111111111111111111111111");
        //创建配置对象
        Configuration configuration = new Configuration(Configuration.getVersion());
        //设置默认生成文件编码
        configuration.setDefaultEncoding("utf-8");
        //设置模板路径
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");
        //获取模板
        Template template = configuration.getTemplate("index.ftl");
        //加载数据
        Map<String, Object> dataModel = new HashMap<String, Object>();
        dataModel.put("premiseName", tSfContract.getPremiseName());
        dataModel.put("ownerName", tSfContract.getOwnerName());
        // dataModel.put("signUserName",tSfContract.getSignUserName());
        dataModel.put("sfContractNo",tSfContract.getSfContractNo());
        dataModel.put("signUserMobile",tSfContract.getSignUserMobile());

        /*dataModel.put("imgCode",imageToStirng());*/
        //创建输出对象,将文件输出到D盘根目录下
        FileWriter fileWriter = new FileWriter("D:/index.doc");
        //渲染模板和数据
        template.process(dataModel, fileWriter);

        //关闭输出
        fileWriter.close();



        return toAjax(tSfContractService.insertTSfContract(tSfContract));
    }



    /*
    新增【请填写功能名称】
    */
    @PreAuthorize(hasPermi = "core:contract:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/saveContrat")
    public AjaxResult saveContract(@RequestBody TSfContract tSfContract)
    {

        return toAjax(tSfContractService.insertTSfContract(tSfContract));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize(hasPermi = "core:contract:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSfContract tSfContract)
    {
        return toAjax(tSfContractService.updateTSfContract(tSfContract));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize(hasPermi = "core:contract:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tSfContractService.deleteTSfContractByIds(ids));
    }
    private TSfContractMapper mapper;
    @PostMapping("csv")
    @ResponseBody
    public String  csv(MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        System.out.println(filename+"1111");
        InputStream inputStream = file.getInputStream();
        System.out.println(inputStream+"22222");
        EasyExcel.read(file.getInputStream(), TSfContract.class, new ContractListenter(mapper)).sheet("Sheet1").doRead();

        return  "success";
    }
}
